﻿using BCCommon;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using WeChatSDK.Common;
using WeChatSDK.WeChatDto.Conversation.ReceivingMessage;

namespace BCService.WeChatComponent.WeChatHandleService
{
    public class WeChatMessageBase:IWeChatMessageBase
    {
        private readonly IConfiguration configuration;
        private static Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
        public WeChatMessageBase(IConfiguration configuration,IServiceProvider serviceProvider)
        {
            this.configuration = configuration;
            if (!bool.Parse(configuration["EnabledWeChat"]))
            {
                return;
            }
            if (keyValuePairs.Count == 0)
            {
                foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    if (type.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IWeChatMessageHandle)))
                    {
                        ConstructorInfo firstConstructor = type.GetTypeInfo().GetConstructors().FirstOrDefault();
                        //获取构造参数列表最多的构造方法
                        foreach (var constructor in type.GetTypeInfo().GetConstructors())
                        {
                            if (constructor.GetParameters().Length > firstConstructor.GetParameters().Length)
                            {
                                firstConstructor = constructor;
                            }
                        }

                        //提取构造参数
                        IEnumerable<object> constructorParameters = firstConstructor.GetParameters().Select(p => serviceProvider.GetService(p.ParameterType));
                        //构建服务实例
                        var service = Activator.CreateInstance(type, constructorParameters.ToArray());
                        keyValuePairs.Add(type.Name.Replace("Service", "Dto"), service);
                    }
                }
            }
        }
        
        public IWeChatMessageHandle GetHandle(ReceivingMessageDto receivingMessageDto)
        {
            if (!bool.Parse(configuration["EnabledWeChat"]))
            {
                throw new ArgumentException("此系统未启动微信支持功能");
            }
            return (IWeChatMessageHandle)keyValuePairs[receivingMessageDto.GetType().Name]; ;
        }
    }
}
